package com.basic.im.pay.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayFundTransOrderQueryRequest;
import com.alipay.api.response.AlipayFundTransOrderQueryResponse;
import com.alipay.util.AliPayParam;
import com.alipay.util.AliPayUtil;
import com.basic.im.api.service.AuthServiceOldUtils;
import com.basic.im.api.service.AuthServiceUtils;
import com.basic.im.api.service.base.AbstractController;
import com.basic.im.comm.constants.KConstants;
import com.basic.im.comm.utils.BeanUtils;
import com.basic.im.comm.utils.DateUtil;
import com.basic.im.comm.utils.ReqUtil;
import com.basic.im.entity.PayConfig;
import com.basic.im.pay.constants.PayResultCode;
import com.basic.im.pay.controller.secondpay.ThirdPay;
import com.basic.im.pay.controller.secondpay.utils.SignUtil;
import com.basic.im.pay.entity.BaseConsumeRecord;
import com.basic.im.pay.service.impl.ConsumeRecordManagerImpl;
import com.basic.im.pay.service.impl.TransfersRecordManagerImpl;
import com.basic.im.room.dao.RoomCoreDao;
import com.basic.im.room.entity.Room;
import com.basic.im.room.service.RoomManager;
import com.basic.im.user.entity.User;
import com.basic.im.user.entity.UserMoneyLog;
import com.basic.im.user.constants.MoneyLogConstants.*;
import com.basic.im.user.service.UserCoreService;
import com.basic.im.user.service.impl.AuthKeysServiceImpl;
import com.basic.im.user.service.impl.UserManagerImpl;
import com.basic.im.utils.ConstantUtil;
import com.basic.im.utils.SKBeanUtils;
import com.basic.im.vo.JSONMessage;
import com.basic.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;


@Api(value="AlipayController",tags="支付宝接口")
@Controller
@RequestMapping(value = "/alipay" ,method={RequestMethod.GET,RequestMethod.POST})
public class AlipayController extends AbstractController {
	
	@Autowired
	private TransfersRecordManagerImpl transfersManager;

	@Autowired
	private ConsumeRecordManagerImpl consumeRecordManager;

	@Autowired
	private UserManagerImpl userManager;

	@Autowired
	private UserCoreService userCoreService;

	@Autowired
	private AuthKeysServiceImpl authKeysService;

	@Autowired
	private AuthServiceUtils authServiceUtils;
	@Autowired
	private AuthServiceOldUtils authServiceOldUtils;
	@Autowired
	private RoomManager roomManager;
	@Autowired
	private RoomCoreDao roomCoreDao;

	@Autowired
	private RedissonClient redissonClient;

	@Value("${tszfaa.paySecret}")
	private String tszfaaSecret;

	public static void main(String[] args) {
//		Map<String, Object> nativeParams = new TreeMap<>();
//		nativeParams.put("mchKey", "46");
//		nativeParams.put("mchOrderNo", "861735210182807");
//		nativeParams.put("serialOrderNo", "SLY12261849428quu1jJxYg"); // 金额单位为分
//		nativeParams.put("nonce", "c9e9a0eaaf566f1fe0c2850894202291");
//		nativeParams.put("payStatus", "SUCCESS");
//		nativeParams.put("amount", "1000");
//		nativeParams.put("timestamp", "1735212631805");
//		nativeParams.put("attach", "100155");
//		nativeParams.put("errorMsg", "ok");
//		nativeParams.put("payTime", "2024/12/26 18:51:25");
//		nativeParams.put("realAmount", "1000");
//
//
//		StringBuilder md5Str = new StringBuilder();
//		nativeParams.forEach((key, value) -> md5Str.append(key).append("=").append(value).append("&"));
//		md5Str.deleteCharAt(md5Str.length() - 1).append("kysqmOi9f5ojr8SuWzK8pgN");
//		String signSecret = SecureUtil.md5(md5Str.toString());
//		System.out.println(signSecret);





        Map<String, Object> nativeParams = new TreeMap<>();
        nativeParams.put("mchId", 20000094);

        nativeParams.put("productId", "8008");
        nativeParams.put("mchOrderNo", StringUtil.getOutTradeNo());
        nativeParams.put("amount", 1000);
        nativeParams.put("notifyUrl", "/alipay/tszfaaCallBack"); // 未初始化
        nativeParams.put("subject","1");
        nativeParams.put("body","香水名");
        nativeParams.put("param1","fasdfasdf");
        nativeParams.put("extra","abcd");
        nativeParams.put("key","1RWGEGISF4GGPDWF2WXDVJ4OCFZKFBKGVZBFQLSLHWKTMYHXN0FYPXZ8BM63KSJ8Z6H0QQIW5W1SSKFVBY64CTZFVEAAKCQUAWLZMHEFYEO7FFBR61L3XWTEJ4FWYS2X");



        StringBuilder md5Str = new StringBuilder();
        StringBuilder finalparam = new StringBuilder();
        nativeParams.forEach((key, value) -> md5Str.append(key).append("=").append(value).append("&"));
        md5Str.deleteCharAt(md5Str.length() - 1);
        String sign = SecureUtil.md5(md5Str.toString()).toUpperCase();
        nativeParams.put("sign", sign);
        nativeParams.forEach((key, value) -> finalparam.append(key).append("=").append(value).append("&"));
        finalparam.deleteCharAt(finalparam.length()-1);

        HttpResponse response = HttpRequest.post("https://wg.kkzf.xyz"+"/api/pay/create_order?"+finalparam)
                .body(JSONUtil.toJsonStr(nativeParams),"application/json; charset=utf-8")
                .timeout(15000)
                .execute();

        System.out.println(response.body());
//        if(response.getStatus() == 200){
//            consumeRecordManager.saveConsumeRecord(entity);
//            logger.info("---------------------{}",response.body());
//            cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(response.body());
//            String code = (String) jsonObject.get("code");
//            if(!"200".equals(code)){
//                return JSONMessage.failure((String) jsonObject.get("msg"));
//            }
//            String payUrl = (String) jsonObject.getJSONObject("data").getJSONObject("url").get("payUrl");
//            map.put("payUrl", payUrl);
//            map.put("orderNo",orderNo);
//            return JSONMessage.success(null,map);
//        }


	}

	@RequestMapping(value = "/tszfaaCallBack", produces = MediaType.TEXT_PLAIN_VALUE)
	@ResponseBody
	public String tszfaaCallBack(@RequestBody Map<String,Object> param) {
	    logger.error("支付返回参数","===============================================================");

        for (Map.Entry<String, Object> entry : param.entrySet()) {

            logger.error(entry.getKey(),entry.getValue());
        }



        logger.error("支付返回参数结束","===============================================================");

		String mchKey = (String) param.get("mchKey");
		String mchOrderNo = (String) param.get("mchOrderNo");
		String serialOrderNo = (String) param.get("serialOrderNo");
		String nonce = (String) param.get("nonce");
		String payStatus = (String) param.get("payStatus");
		Integer amount = (Integer) param.get("amount");
		String timestamp = (String) param.get("timestamp");
		String sign = (String) param.get("sign");
		String attach = (String) param.get("attach");

		String errorMsg = (String) param.get("errorMsg");
		String payTime = (String) param.get("payTime");
		Integer realAmount = (Integer) param.get("realAmount");





		Map<String, Object> nativeParams = new TreeMap<>();
		nativeParams.put("mchKey", mchKey);
		nativeParams.put("mchOrderNo", mchOrderNo);
		nativeParams.put("serialOrderNo", serialOrderNo); // 金额单位为分
		nativeParams.put("nonce", nonce);
		nativeParams.put("payStatus", payStatus);
		nativeParams.put("amount", amount);
		nativeParams.put("timestamp", timestamp);
		nativeParams.put("attach", attach);
		nativeParams.put("errorMsg", errorMsg);
		nativeParams.put("payTime", payTime);
		nativeParams.put("realAmount", realAmount);

		StringBuilder md5Str = new StringBuilder();
		nativeParams.forEach((key, value) -> md5Str.append(key).append("=").append(value).append("&"));
		md5Str.deleteCharAt(md5Str.length() - 1).append(tszfaaSecret);
		String signSecret = SecureUtil.md5(md5Str.toString());
		if(signSecret.equals(sign)){
			switch (payStatus){
				case "SUCCESS":
				{
					BaseConsumeRecord entity = consumeRecordManager.getConsumeRecordByNo(mchOrderNo);
					if (null == entity) {
						logger.info("交易订单号不存在！-----" + mchOrderNo);
					} else if (0 != entity.getStatus()) {
						logger.info(mchOrderNo + "===status===" + entity.getStatus() + "=======交易已处理或已取消!");
					} else {
						entity.setStatus(KConstants.OrderStatus.END);
						UserMoneyLog userMoneyLog = new UserMoneyLog(entity.getUserId(), 0, mchOrderNo, entity.getMoney(),
								MoenyAddEnum.MOENY_ADD, MoneyLogEnum.RECHARGE, MoneyLogTypeEnum.NORMAL_PAY);

						userMoneyLog.setExtra("aipayzf_PAY");
						Double balance = userCoreService.rechargeUserMoenyV1(userMoneyLog);

						entity.setOperationAmount(entity.getMoney());
						entity.setCurrentBalance(balance);
						consumeRecordManager.getConsumeRecordDao().update(entity.getId(), entity);

						redissonClient.getSet("USER_FIRST_RECHARGE").add(attach);

					}
					return "SUCCESS";
				}
				case "FAIL":
				case "TIMEOUT":
				case "CLOSE":
				{
					BaseConsumeRecord entity = consumeRecordManager.getConsumeRecordByNo(mchOrderNo);
					if (null == entity) {
						logger.info("交易订单号不存在！-----" + mchOrderNo);
					} else if (0 != entity.getStatus()) {
						logger.info(mchOrderNo + "===status===" + entity.getStatus() + "=======交易已处理或已取消!");
					} else {
						entity.setStatus(KConstants.OrderStatus.PAST);
						consumeRecordManager.getConsumeRecordDao().update(entity.getId(), entity);
					}
				}
				return "SUCCESS";
			}
		}
		return "FAIL";
	}



    @RequestMapping(value = "/thirdnotify", produces = MediaType.TEXT_PLAIN_VALUE)
    @ResponseBody
    public String thirdnotify(@RequestBody Map<String,Object> param) {
        logger.error("支付返回参数","===============================================================");

        for (Map.Entry<String, Object> entry : param.entrySet()) {

            logger.error(entry.getKey(),entry.getValue().toString());
        }



        logger.error("支付返回参数结束","===============================================================");

        String status = (String) param.get("status");
        String merch_no = (String) param.get("merch_no");
        String merch_order_no = (String) param.get("merch_order_no");
        String order_no = (String) param.get("order_no");
        String amount = (String) param.get("amount");
        Integer order_amount = (Integer) param.get("order_amount");
        String order_currency = (String) param.get("order_currency");
        String channel_code = (String) param.get("channel_code");
        String sign = (String) param.get("sign");





        Map<String, Object> nativeParams = new TreeMap<>();
        nativeParams.put("merch_no", merch_no);
        nativeParams.put("merch_order_no", merch_order_no);
        nativeParams.put("order_no", order_no);
        nativeParams.put("amount", amount);
        nativeParams.put("order_amount", order_amount);
        nativeParams.put("order_currency", order_currency);
        nativeParams.put("channel_code", channel_code);


        String signSecret = SignUtil.getSign2(nativeParams,ThirdPay.MERCHANT_KEY);
        if(signSecret.equals(sign)){
            switch (status){
                case "success":
                {
                    BaseConsumeRecord entity = consumeRecordManager.getConsumeRecordByNo(merch_order_no);
                    if (null == entity) {
                        logger.info("交易订单号不存在！-----" + merch_order_no);
                    } else if (0 != entity.getStatus()) {
                        logger.info(merch_order_no + "===status===" + entity.getStatus() + "=======交易已处理或已取消!");
                    } else {
                        entity.setStatus(KConstants.OrderStatus.END);
                        UserMoneyLog userMoneyLog = new UserMoneyLog(entity.getUserId(), 0, merch_order_no, entity.getMoney(),
                                MoenyAddEnum.MOENY_ADD, MoneyLogEnum.RECHARGE, MoneyLogTypeEnum.NORMAL_PAY);

                        userMoneyLog.setExtra("aipayzf_PAY");
                        Double balance = userCoreService.rechargeUserMoenyV1(userMoneyLog);

                        entity.setOperationAmount(entity.getMoney());
                        entity.setCurrentBalance(balance);
                        consumeRecordManager.getConsumeRecordDao().update(entity.getId(), entity);

                        redissonClient.getSet("USER_FIRST_RECHARGE").add(entity.getUserId());

                    }
                    return "SUCCESS";
                }
                case "fail":
                case "TIMEOUT":
                case "CLOSE":
                {
                    BaseConsumeRecord entity = consumeRecordManager.getConsumeRecordByNo(merch_order_no);
                    if (null == entity) {
                        logger.info("交易订单号不存在！-----" + merch_order_no);
                    } else if (0 != entity.getStatus()) {
                        logger.info(merch_order_no + "===status===" + entity.getStatus() + "=======交易已处理或已取消!");
                    } else {
                        entity.setStatus(KConstants.OrderStatus.PAST);
                        consumeRecordManager.getConsumeRecordDao().update(entity.getId(), entity);
                    }
                }
                return "SUCCESS";
            }
        }
        return "FAIL";
    }



    @RequestMapping(value = "/notify")
    @ResponseBody
    public String notify(HttpServletRequest request) throws IOException {

        if(StringUtils.isEmpty(request.getParameter("sign"))){   //sign参数 不存在
            return "fail(sign not exists)";
        }

        String resSign = request.getParameter("sign");  //接口返回sign参数值

        Map<String, Object> paramsMap = new TreeMap<>();
        paramsMap.put("payOrderId", request.getParameter("payOrderId"));
        paramsMap.put("mchId", request.getParameter("mchId"));
        paramsMap.put("appId", request.getParameter("appId"));
        paramsMap.put("productId", request.getParameter("productId"));
        paramsMap.put("mchOrderNo", request.getParameter("mchOrderNo"));
        paramsMap.put("amount", request.getParameter("amount"));
        paramsMap.put("status", request.getParameter("status"));
        paramsMap.put("channelOrderNo", request.getParameter("channelOrderNo"));
        paramsMap.put("channelAttach", request.getParameter("channelAttach"));
        paramsMap.put("param1", request.getParameter("param1"));
        paramsMap.put("param2", request.getParameter("param2"));
        paramsMap.put("paySuccTime", request.getParameter("paySuccTime"));
        paramsMap.put("backType", request.getParameter("backType"));
        paramsMap.put("income", request.getParameter("income"));
        paramsMap.put("reqTime", request.getParameter("reqTime"));

        logger.error("支付返回参数","===============================================================");

        for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {

            logger.error(entry.getKey(),entry.getValue().toString());
        }



        logger.error("支付返回参数结束","===============================================================");

        String sign = SignUtil.getSign(paramsMap, ThirdPay.MERCHANT_KEY);   //根据返回数据 和商户key 生成sign

        //验签
        if(!resSign.equals(sign)){
            return "fail(verify fail)";
        }

        String mchOrderNo = request.getParameter("mchOrderNo");

        //处理业务...

        switch (request.getParameter("status")){
            case "2":
            {
                BaseConsumeRecord entity = consumeRecordManager.getConsumeRecordByNo(mchOrderNo);
                if (null == entity) {
                    logger.info("交易订单号不存在！-----" + mchOrderNo);
                } else if (0 != entity.getStatus()) {
                    logger.info(mchOrderNo + "===status===" + entity.getStatus() + "=======交易已处理或已取消!");
                } else {
                    entity.setStatus(KConstants.OrderStatus.END);
                    UserMoneyLog userMoneyLog = new UserMoneyLog(entity.getUserId(), 0, mchOrderNo, entity.getMoney(),
                            MoenyAddEnum.MOENY_ADD, MoneyLogEnum.RECHARGE, MoneyLogTypeEnum.NORMAL_PAY);

                    userMoneyLog.setExtra("aipayzf_PAY");
                    Double balance = userCoreService.rechargeUserMoenyV1(userMoneyLog);

                    entity.setOperationAmount(entity.getMoney());
                    entity.setCurrentBalance(balance);
                    consumeRecordManager.getConsumeRecordDao().update(entity.getId(), entity);

                    redissonClient.getSet("USER_FIRST_RECHARGE").add(request.getParameter("param1"));

                }
                return "success";
            }
            case "0":
            case "1":
            case "3":
            {
                BaseConsumeRecord entity = consumeRecordManager.getConsumeRecordByNo(mchOrderNo);
                if (null == entity) {
                    logger.info("交易订单号不存在！-----" + mchOrderNo);
                } else if (0 != entity.getStatus()) {
                    logger.info(mchOrderNo + "===status===" + entity.getStatus() + "=======交易已处理或已取消!");
                } else {
                    entity.setStatus(KConstants.OrderStatus.PAST);
                    consumeRecordManager.getConsumeRecordDao().update(entity.getId(), entity);
                }
            }
            return "success";
        }

        return "success";
    }



	@ApiOperation("支付宝支付回调")
	@RequestMapping("/callBack")
	@ResponseBody
	public String payCheck(HttpServletRequest request, HttpServletResponse response){
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
		    String name = (String) iter.next();
		    String[] values = (String[]) requestParams.get(name);
		    String valueStr = "";
		    for (int i = 0; i < values.length; i++) {
		        valueStr = (i == values.length - 1) ? valueStr + values[i]
		                    : valueStr + values[i] + ",";
		  	}
		    //乱码解决，这段代码在出现乱码时使用。
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		try {
			String tradeNo = params.get("out_trade_no");
			String tradeStatus=params.get("trade_status");
			logger.info("订单号    "+tradeNo);
			boolean flag = AlipaySignature.rsaCheckV1(params,AliPayUtil.ALIPAY_PUBLIC_KEY, AliPayUtil.CHARSET,"RSA2");
			if(flag){
				BaseConsumeRecord entity = consumeRecordManager.getConsumeRecordByNo(tradeNo);
				if(null==entity) {
					logger.info("订单号  错误 不存在 {} ", tradeNo);
					return "failure";
				}
				if(entity.getStatus()!= KConstants.OrderStatus.END&&"TRADE_SUCCESS".equals(tradeStatus)){
					//把支付宝返回的订单信息存到数据库
					AliPayParam aliCallBack=new AliPayParam();
					BeanUtils.populate(aliCallBack, params);
					consumeRecordManager.getConsumeRecordDao().saveEntity(aliCallBack);
					User user=userManager.getUser(entity.getUserId());
					user.setAliUserId(aliCallBack.getBuyer_id());

					if (entity.getChangeType() == MoenyAddEnum.MOENY_ADD.getType()){
						UserMoneyLog userMoneyLog =new UserMoneyLog(entity.getUserId(),0,tradeNo,entity.getMoney(),
								MoenyAddEnum.MOENY_ADD, MoneyLogEnum.CASH_OUT, MoneyLogTypeEnum.NORMAL_PAY);
						userMoneyLog.setExtra("ALI_PAY");
						userManager.rechargeUserMoenyV1(userMoneyLog);
						Double balance = userManager.getUserMoenyV1(entity.getUserId());
						entity.setCurrentBalance(balance);
					}

					entity.setStatus(KConstants.OrderStatus.END);
					entity.setOperationAmount(entity.getMoney());
					//如果是付费入群业务
					if(entity.getType() == KConstants.ConsumeType.ADD_ROOM){
						//付费入群.加入群聊
						int periods = entity.getNum()==0?1:entity.getNum();
						roomManager.paySuccess(entity.getUserId(),entity.getTargetId(), KConstants.Room_Role.MEMBER,
								Room.Member.OperationType.INVITE_PAY,periods);
						//群主增加余额
						String tradeNo1= com.basic.utils.StringUtil.getOutTradeNo();
						Room room = roomCoreDao.getRoomById(entity.getTargetId());
						UserMoneyLog userMoneyLog =new UserMoneyLog(room.getUserId(),0,tradeNo1,entity.getMoney(),
								MoenyAddEnum.MOENY_ADD, MoneyLogEnum.JOIN_ROOM_PAY, MoneyLogTypeEnum.RECEIVE);
						userMoneyLog.setExtra("WX_PAY");
						userManager.rechargeUserMoenyV1(userMoneyLog);
						Double balance = userManager.getUserMoenyV1(entity.getUserId());
						entity.setCurrentBalance(balance);
						BaseConsumeRecord record=new BaseConsumeRecord();
						record.setUserId(room.getUserId());
						record.setToUserId(0);
						record.setTradeNo(tradeNo1);
						record.setMoney(entity.getMoney());
						record.setOperationAmount(entity.getMoney());
						record.setCurrentBalance(balance);
						record.setBusinessId(userMoneyLog.getBusinessId());
						record.setStatus(KConstants.OrderStatus.END);
						record.setType(KConstants.ConsumeType.ADD_ROOM);
						record.setChangeType(KConstants.MOENY_ADD);
						record.setPayType(KConstants.PayType.ALIPAY); //余额支付
						record.setDesc("付费收益");
						//record.setDesc("Paid income");
						record.setTime(com.basic.utils.DateUtil.currentTimeSeconds());
						consumeRecordManager.saveConsumeRecord(record);
					}

					consumeRecordManager.getConsumeRecordDao().update(entity.getId(), entity);
					logger.info("支付宝支付成功 {}",tradeNo);
					return "success";
				}else if("TRADE_CLOSED".equals(tradeStatus)) {
					logger.info("订单号  已取消  {}  ",tradeNo);
					consumeRecordManager.getConsumeRecordDao().updateAttribute(entity.getId(), "status", -1);
					return "success";
				}

			}else{
				logger.info("支付宝回调失败"+flag);
				return "failure";
			}
		} catch (AlipayApiException e) {
			logger.error(e.getMessage(),e);
		}
		return "failure";
	}
	
	/**
	 * 支付宝提现
	 * @param amount
	 * @param time
	 * @param secret
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "/transfer")
	@ApiOperation("支付宝提现")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType="query" , name="amount" , value="数量",dataType="String",required=true),
			@ApiImplicitParam(paramType="query" , name="time" , value="时间",dataType="long",required=true,defaultValue = "0"),
			@ApiImplicitParam(paramType="query" , name="secret" , value="秘钥",dataType="int",required=true),
			@ApiImplicitParam(paramType="query" , name="salt" , value="盐",dataType="int",required=true),
			@ApiImplicitParam(paramType="query" , name="callback" , value="回调",dataType="String",required=true)
	})
	@ResponseBody
	public JSONMessage transfer(@RequestParam(defaultValue="") String amount,@RequestParam(defaultValue="0") long time,
			@RequestParam(defaultValue="") String secret, String callback,String salt){
		if(true){
			return JSONMessage.failureByErrCode(KConstants.ResultCode.PleaseUpgradeLatestVersion);
		}
		if(1 != SKBeanUtils.getImCoreService().getClientConfig().getEnableAliPay()){
			return JSONMessage.failureByErrCode(KConstants.ResultCode.FUNCTION_NOTOPEN);
		}
		if(StringUtil.isEmpty(amount)) {
			return JSONMessage.failureByErrCode(PayResultCode.NoTransferMoney);
		}

		int userId = ReqUtil.getUserId();
		User user=userManager.getUserDao().get(userId);
		String token = getAccess_token();
		String	aliUserId=authKeysService.getAliUserId(userId);
		if(StringUtil.isEmpty(aliUserId)){
			aliUserId=user.getAliUserId();
			if(StringUtil.isEmpty(aliUserId)) {
				return JSONMessage.failureByErrCode(PayResultCode.NotAliAuth);
			}
		}
		if(StringUtil.isEmpty(salt)){
			if(!authServiceOldUtils.authWxTransferPay(user.getPayPassword(),userId+"", token, amount,user.getAliUserId(),time, secret)){
				return JSONMessage.failureByErrCode(KConstants.ResultCode.AUTH_FAILED);
			}
		}
		// 提现金额
		double total=(Double.valueOf(amount));
		PayConfig payConfig = SKBeanUtils.getImCoreService().getPayConfig();
		if(Double.valueOf(amount)< SKBeanUtils.getImCoreService().getPayConfig().getMinWithdrawAmount()){
			return JSONMessage.failureByErrCode(PayResultCode.WithdrawMin);
		}
		if(SKBeanUtils.getImCoreService().getPayConfig().getMaxWithdrawAmount()<total) {
			return JSONMessage.failureByErrCode(PayResultCode.TransferMaxMoney);
		}
		// 判断用户单日消费金额
		Double todayMoney = consumeRecordManager.getUserPayMoney(userId,KConstants.ConsumeType.PUT_RAISE_CASH,KConstants.OrderStatus.END,DateUtil.getTodayMorning().getTime()/1000 ,DateUtil.getTodayNight().getTime()/1000);
		todayMoney = todayMoney + total;
		if(todayMoney> SKBeanUtils.getImCoreService().getPayConfig().getDayMaxWithdrawAmount()){
			return JSONMessage.failureByErrCode(PayResultCode.ExceedDayMaxAmount);
		}

		user.setAliUserId(aliUserId);
		return transfersManager.aliWithdrawalPay(user, amount);

	}
	/**
	 * 支付宝提现
	 * @return
	 */
	@RequestMapping(value = "/transfer/v1")
	@ApiOperation("支付宝提现")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType="query" , name="data" , value="加密参数",dataType="String",required=true,defaultValue = ""),
			@ApiImplicitParam(paramType="query" , name="codeId" , value="编号",dataType="String",required=true,defaultValue = ""),
			@ApiImplicitParam(paramType="query" , name="callback" , value="回调参数",dataType="String",required=true)
	})
	@ResponseBody
	public JSONMessage transferV1(@RequestParam(defaultValue="") String data,
	@RequestParam(defaultValue="") String codeId, String callback){
		if(1 != SKBeanUtils.getImCoreService().getClientConfig().getEnableAliPay()){
			return JSONMessage.failureByErrCode(KConstants.ResultCode.FUNCTION_NOTOPEN);
		}
		int userId = ReqUtil.getUserId();
		String token = getAccess_token();
		User user=userManager.getUser(userId);
		String	aliUserId=authKeysService.getAliUserId(userId);
		if(StringUtil.isEmpty(aliUserId)){
			aliUserId=user.getAliUserId();
			if(StringUtil.isEmpty(aliUserId)) {
				return JSONMessage.failureByErrCode(PayResultCode.NotAliAuth);
			}
		}
		String payPayPassword = authKeysService.getPayPassword(userId);
		JSONObject jsonObj = authServiceUtils.authAliWithdrawalPay(userId, token, data, codeId,payPayPassword);
		if(null==jsonObj) {
			return JSONMessage.failureByErrCode(KConstants.ResultCode.AUTH_FAILED);
		}
		String amount = jsonObj.getString("amount");
		if(StringUtil.isEmpty(amount)) {
			return JSONMessage.failureByErrCode(PayResultCode.NoTransferMoney);
		}
		// 提现金额
		double total=(Double.valueOf(amount));
		if(SKBeanUtils.getImCoreService().getPayConfig().getMaxWithdrawAmount()<total) {
			return JSONMessage.failureByErrCode(PayResultCode.TransferMaxMoney);
		}
		// 判断用户单日消费金额
		Double todayMoney = consumeRecordManager.getUserPayMoney(userId,KConstants.ConsumeType.PUT_RAISE_CASH,KConstants.OrderStatus.END,DateUtil.getTodayMorning().getTime()/1000 ,DateUtil.getTodayNight().getTime()/1000);
		todayMoney = todayMoney + total;
		if(todayMoney>SKBeanUtils.getImCoreService().getPayConfig().getDayMaxWithdrawAmount()){
			return JSONMessage.failureByErrCode(PayResultCode.ExceedDayMaxAmount);
		}
		user.setAliUserId(aliUserId);
		return transfersManager.aliWithdrawalPay(user, amount);

		}


	
	/**
	 * 支付宝提现查询
	 * @param tradeno
	 * @param callback
	 * @return
	 */
	@RequestMapping(value ="/aliPayQuery")
	@ApiOperation("支付宝提现查询")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType="query" , name="callback" , value="回调参数",dataType="String",required=true),
			@ApiImplicitParam(paramType="query" , name="tradeno" , value="交易",dataType="String",required=true)
	})
	@ResponseBody
	public JSONMessage aliPayQuery(String tradeno,String callback){
		if (StringUtil.isEmpty(tradeno)) {
			return null;
		}
		AlipayFundTransOrderQueryRequest request = new AlipayFundTransOrderQueryRequest();
		request.setBizContent("{" +
				"\"out_biz_no\":\""+tradeno+"\"," + // 订单号
				"\"order_id\":\"\"" +
				"  }");
		try {
			AlipayFundTransOrderQueryResponse response = AliPayUtil.getAliPayClient().execute(request);
			logger.info("支付返回结果  "+response.getCode());
			if(response.isSuccess()){
				logger.info("调用成功");
			} else {
				logger.info("调用失败");
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}

		return JSONMessage.success();
	}
}
